package www.yingdi365.com.activity;

import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;

import www.yingdi365.com.R;
import www.yingdi365.com.base.ZjbBaseActivity;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.model.AppMicrofacies;
import www.yingdi365.com.model.QingJianBean;
import www.yingdi365.com.photoview.PhotoView;
import www.yingdi365.com.photoview.PhotoViewAttacher;
import www.yingdi365.com.util.DpUtils;
import www.yingdi365.com.util.GsonUtils;
import www.yingdi365.com.util.LogUtil;
import www.yingdi365.com.util.ScreenUtils;

public class BianJiQJActivity extends ZjbBaseActivity implements View.OnClickListener {

    private QingJianBean pagesBean;
    private AbsoluteLayout viewAbsolute;
    private ImageView imageBg;
    private TextView textViewRight;
    private EditText[] textViews;
    private PhotoView[] imageViews;
    private ImageView[] imagePickers;
    private boolean[] isPickPic;
    private int position;
    private float baiFenBiWidth;
    private float baiFenBiHeigh;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bian_ji_qj);
        init();
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        pagesBean = (QingJianBean) intent.getSerializableExtra(Constant.INTENT_KEY.pagesBean);
        position = intent.getIntExtra(Constant.INTENT_KEY.Position, -1);
        for (int i = 0; i < pagesBean.getItems().size(); i++) {
            QingJianBean.ItemsBeanX itemsBeanX = pagesBean.getItems().get(i);
            itemsBeanX.setIndex(i);
        }
        textViews = new EditText[pagesBean.getItems().size()];
        imageViews = new PhotoView[pagesBean.getItems().size()];
        imagePickers = new ImageView[pagesBean.getItems().size()];
        isPickPic = new boolean[pagesBean.getItems().size()];
    }

    @Override
    protected void findID() {
        viewAbsolute = (AbsoluteLayout) findViewById(R.id.viewAbsolute);
        imageBg = (ImageView) findViewById(R.id.imageBg);
        textViewRight = (TextView) findViewById(R.id.textViewRight);
    }

    @Override
    protected void initViews() {
        ((TextView) findViewById(R.id.textViewTitle)).setText("编辑请柬");
        textViewRight.setText("保存");
        ViewGroup.LayoutParams layoutParams = viewAbsolute.getLayoutParams();
        int screenWidth = ScreenUtils.getScreenWidth(this);
        float width = screenWidth - DpUtils.convertDpToPixel(20f, this);
        float height = width * 1.4375f;//height is ready
        layoutParams.width = (int) width;
        layoutParams.height = (int) height;
        viewAbsolute.setLayoutParams(layoutParams);
        if (pagesBean.getItems().size() == 0 && TextUtils.isEmpty(pagesBean.getBgImage())) {
            Glide.with(this)
                    .load(pagesBean.getPreview())
                    .into(imageBg);
        } else {
            baiFenBiWidth = width / 640f;
            baiFenBiHeigh = height / 920f;
            Glide.with(BianJiQJActivity.this)
                    .load(pagesBean.getBgImage())
                    .into(imageBg);
            for (int i = 0; i < pagesBean.getItems().size(); i++) {
                final QingJianBean.ItemsBeanX itemsBean = pagesBean.getItems().get(i);
                switch (itemsBean.getType()) {
                    case "picture":
                        final QingJianBean.ItemsBeanX.PictureBeanX pictureBean = itemsBean.getPicture();
                        float vx = (float) (pictureBean.getVx()) * baiFenBiWidth;
                        float vy = (float) (pictureBean.getVy()) * baiFenBiHeigh;
                        float vWidth = (float) (pictureBean.getVwidth()) * baiFenBiWidth;
                        float vHeight = (float) (pictureBean.getVheight()) * baiFenBiHeigh;
                        imageViews[itemsBean.getIndex()] = new PhotoView(BianJiQJActivity.this);
                        imageViews[itemsBean.getIndex()].setLayoutParams(new AbsoluteLayout.LayoutParams((int) vWidth, (int) vHeight, (int) vx, (int) vy));
                        imageViews[itemsBean.getIndex()].setScaleType(ImageView.ScaleType.CENTER_CROP);
                        Glide.with(BianJiQJActivity.this)
                                .load(pictureBean.getUrl() + Constant.TuPianYaSuo).listener(new RequestListener<String, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                if (itemsBean.isDiy()) {
                                    float scaleW = (float) (pictureBean.getWidth()) / (float) (pictureBean.getVwidth());
                                    float scaleH = (float) (pictureBean.getHeight()) / (float) (pictureBean.getVheight());
                                    float scale = scaleH > scaleW ? scaleW : scaleH;
                                    imageViews[itemsBean.getIndex()].zoomToQuick(scale, (float) (pictureBean.getX() - pictureBean.getVx()) * baiFenBiWidth, (float) (pictureBean.getY() - pictureBean.getVy()) * baiFenBiHeigh);
                                }
                                return false;
                            }
                        })
                                .into(new SimpleTarget<GlideDrawable>() {
                                    @Override
                                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                                        imageViews[itemsBean.getIndex()].setImageDrawable(resource);
                                    }
                                });
                        viewAbsolute.addView(imageViews[itemsBean.getIndex()]);
                        if (itemsBean.isDiy()) {
                            isPickPic[itemsBean.getIndex()] = false;
                            imagePickers[itemsBean.getIndex()] = new ImageView(BianJiQJActivity.this);
                            imagePickers[itemsBean.getIndex()].setLayoutParams(new AbsoluteLayout.LayoutParams((int) (67 * baiFenBiWidth), (int) (96 * baiFenBiHeigh), (int) (vx + vWidth / 2 - 33.5f * baiFenBiWidth), (int) (vy + vHeight / 2 - 48f * baiFenBiHeigh)));
                            imagePickers[itemsBean.getIndex()].setImageResource(R.mipmap.pick_pic);
                            viewAbsolute.addView(imagePickers[itemsBean.getIndex()]);
                            imagePickers[itemsBean.getIndex()].setVisibility(View.GONE);
                            imageViews[itemsBean.getIndex()].setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                                @Override
                                public void onPhotoTap(View view, float x, float y) {
                                    isPickPic[itemsBean.getIndex()] = !isPickPic[itemsBean.getIndex()];
                                    if (isPickPic[itemsBean.getIndex()]) {
                                        imagePickers[itemsBean.getIndex()].setVisibility(View.VISIBLE);
                                    } else {
                                        imagePickers[itemsBean.getIndex()].setVisibility(View.GONE);
                                    }
                                }
                            });
                            imagePickers[itemsBean.getIndex()].setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent();
                                    intent.setClass(BianJiQJActivity.this, XuanZeZPActivity.class);
                                    intent.putExtra(Constant.INTENT_KEY.Position, itemsBean.getIndex());
                                    startActivityForResult(intent, Constant.REQUEST_RESULT_CODE.IMAGE_PICKER);
                                }
                            });
                        }
                        break;
                    case "text":
                        QingJianBean.ItemsBeanX.TextBeanX textBeanX = itemsBean.getText();
                        float vx1 = (float) (textBeanX.getX()) * baiFenBiWidth;
                        float vy1 = (float) (textBeanX.getY()) * baiFenBiHeigh;
                        float vWidth1 = (float) (textBeanX.getWidth()) * baiFenBiWidth;
                        float vHeight1 = (float) (textBeanX.getHeight()) * baiFenBiHeigh * 1.2f;
                        textViews[itemsBean.getIndex()] = new EditText(BianJiQJActivity.this);
                        textViews[itemsBean.getIndex()].setLayoutParams(new AbsoluteLayout.LayoutParams((int) vWidth1, (int) (vHeight1 * 1.8f), (int) vx1, (int) vy1 - (int) (0.3f * vHeight1)));
                        textViews[itemsBean.getIndex()].setTextSize(DpUtils.convertPixelsToDp(Float.parseFloat(textBeanX.getFontSize()) * baiFenBiWidth, BianJiQJActivity.this));
                        textViews[itemsBean.getIndex()].setGravity(Gravity.CENTER);
                        textViews[itemsBean.getIndex()].setText(textBeanX.getContent());
                        textViews[itemsBean.getIndex()].setBackgroundResource(R.drawable.shape_edittext_bianji_5dp);
                        textViews[itemsBean.getIndex()].setSelection(textBeanX.getContent().length());
                        viewAbsolute.addView(textViews[itemsBean.getIndex()]);
                        break;
                }
            }
        }
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageBack).setOnClickListener(this);
        textViewRight.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        imageBg.postDelayed(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < pagesBean.getItems().size(); i++) {
                    if (!pagesBean.getItems().get(i).isDiy()) {
                        if (imageViews[i] != null) {
                            imageViews[i].setZoomable(false);
                        }
                    }
                }
            }
        }, 500);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_RESULT_CODE.IMAGE_PICKER && resultCode == Constant.REQUEST_RESULT_CODE.IMAGE_PICKER) {
            AppMicrofacies.PictureListBean PictureListBean = (AppMicrofacies.PictureListBean) data.getSerializableExtra(Constant.INTENT_KEY.PictureListBean);
            final int index = data.getIntExtra(Constant.INTENT_KEY.Position, -1);
            pagesBean.getItems().get(index).getPicture().setUrl(PictureListBean.getUrl());
            imageViews[index].clearZoom();
            Glide.with(BianJiQJActivity.this)
                    .load(PictureListBean.getUrl()+Constant.TuPianYaSuo)
                    .placeholder(R.mipmap.album)
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            imageViews[index].zoomToQuick(1,0,0);
                            return false;
                        }
                    })
                    .into(new SimpleTarget<GlideDrawable>() {
                        @Override
                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                            imageViews[index].setImageDrawable(resource);
                        }
                    });
//                    .into(imageViews[index]);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textViewRight:
                for (int i = 0; i < pagesBean.getItems().size(); i++) {
                    QingJianBean.ItemsBeanX itemsBeanX = pagesBean.getItems().get(i);
                    String type = itemsBeanX.getType();
                    if (TextUtils.equals(type, "picture")) {
                        if (itemsBeanX.isDiy()) {
                            RectF displayRect = imageViews[i].getDisplayRect();
                            QingJianBean.ItemsBeanX.PictureBeanX picture = itemsBeanX.getPicture();
                            picture.setX((int) (picture.getVx() + displayRect.left / baiFenBiWidth));
                            picture.setY((int) (picture.getVy() + displayRect.top / baiFenBiHeigh));
                            picture.setWidth((int) ((displayRect.right - displayRect.left) / baiFenBiWidth));
                            picture.setHeight((int) ((displayRect.bottom - displayRect.top) / baiFenBiHeigh));
                        }
                    } else {
                        itemsBeanX.getText().setContent(textViews[i].getText().toString().trim());
                    }
                }
                LogUtil.LogShitou("BianJiQJActivity--onClick", "" + GsonUtils.parseObject(pagesBean));
                Intent intent = new Intent();
                intent.setAction(Constant.BROADCASTCODE.QingJianBaoCun);
                intent.putExtra(Constant.INTENT_KEY.pagesBean, pagesBean);
                intent.putExtra(Constant.INTENT_KEY.Position, position);
                sendBroadcast(intent);
                finish();
                break;
            case R.id.imageBack:
                finish();
                break;
        }
    }
}
